package com.sigmatrix.h5.auth;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import com.sigmatrix.h5.entity.v2.DisPermission;

/**
 * 默认访问控制类。
 * url的权限不支持or的关系。只支持and关系。
 * 
 * @author wei.wang
 *
 */
@Service
public class DefaultAuthorization implements IAuthorize {

	/**
	 * url-match
	 */
	private  PathMatcher pathMatcher = new AntPathMatcher();
	
	@Override
	public boolean isAccessAllowed(String url, LoginSession session) {
		//获取这个url 依赖的权限。
		Collection<String> dependPermissions = getPermissions(url);
		if(dependPermissions==null||dependPermissions.isEmpty()){
			return true;
		}
		//获取当前用拥有的权限。
		Collection<DisPermission> havePermissions = session.getPermissions();
		
//		报：illegalStateException:duplicate key
//		Map<String, DisPermission> havePermMap = 
//		havePermissions.stream().collect(Collectors.toMap(DisPermission::getCode, permission -> permission));

		//是否有权限。
		if(havePermissions==null||havePermissions.isEmpty()){
			return false;
		}
		
		Map<String, DisPermission> havePermMap = new HashMap<>();
		for (DisPermission disPermission : havePermissions) {
			havePermMap.put(disPermission.getCode(), disPermission);
		}
		
		//权限判断是否满足
		for (String permission : dependPermissions) {
			if(havePermMap.get(permission)==null){
				return false;
			}
		}
		return true;
	}

	@Override
	public Collection<String> getPermissions(String url) {
		Map<String, String[]> resPermissionMap = ResoursePermissionMap.getResPermissionMap();
		for (String urlPattern : resPermissionMap.keySet()) {
			if(pathMatcher.match(urlPattern, url)){
				String[] strings = resPermissionMap.get(urlPattern);
				return Arrays.asList(strings);
			}
		}
		return null;
	}

}
